package braden.cis.uab.edu;

import java.util.ArrayList;

import braden.cis.uab.edu.automaton.Automaton;
import braden.cis.uab.edu.automaton.State;
import braden.cis.uab.edu.automaton.Transition;
import braden.cis.uab.edu.grammar.Rule;

public class ModelConverter {
	
	public static ArrayList<Rule> automatonToGrammar(Automaton automaton) {
		
		ArrayList<Rule> grammarRules = new ArrayList<Rule>();
		
		for (State state : automaton.getStates()) {
			
			Rule newRule = new Rule(Character.toChars(state.getLabel()+65)[0], state.isInitial());
			
			for (Transition transition : state.getTransitions()) {
				
				for (char character : transition.getLabels()) {
					
					if (character == 'ɛ') {
						newRule.addResult(Character.toString(Character.toChars(transition.getEndState().getLabel()+65)[0]));
					} else {
						newRule.addResult(Character.toString(character) + Character.toString(Character.toChars(transition.getEndState().getLabel()+65)[0]));
					}
				}
			}
			
			if (state.isFinal()) {
				newRule.addResult("ɛ");
			}
			
			if (state.isInitial()) {
				newRule.setStart(true);
			}
			
			grammarRules.add(newRule);
		}
				
		return grammarRules;
	}

	private static void printGrammar(ArrayList<Rule> grammarRules) {
		
		for (Rule rule : grammarRules) {
			System.out.println(rule.getVariable());
			System.out.println("--->");
			for (char[] result : rule.getResults()) {
				for (int i = 0; i<result.length; i++) {
					System.out.print(result[i]+",");
				}
				System.out.println();
			}
			System.out.println("********************************");
		}
	}
}
